package main

import (
	"encoding/json"
	"html/template"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"net/http/httputil"
	"net/url"

	"github.com/julienschmidt/httprouter"
)

// HomePage 主页需要的数据
type HomePage struct {
	Name string
}

// UserPage 用户页使用的数据
type UserPage struct {
	Name string
}

// homeHandler 主页
func homeHandler(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
	cname, err1 := r.Cookie("username")
	sid, err2 := r.Cookie("session")
	// 未登录
	if err1 != nil || err2 != nil {
		name := &HomePage{Name: "test"}
		t, e := template.ParseFiles("./templates/home.html")
		if e != nil {
			log.Printf("ParseFiles home.html error: %v", e)
			return
		}
		t.Execute(w, name)
		return
	}
	// 登录重定向
	if len(cname.Value) != 0 && len(sid.Value) != 0 {
		http.Redirect(w, r, "/userhome", http.StatusFound) //重定向
		return
	}
}

func userHomeHandler(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	cname, err1 := r.Cookie("username")
	_, err2 := r.Cookie("session")
	if err1 != nil || err2 != nil { //session
		http.Redirect(w, r, "/", http.StatusFound)
		return
	}
	fname := r.FormValue("username") // 表单登录
	var p *UserPage
	if len(cname.Value) != 0 {
		p = &UserPage{Name: cname.Value}
	} else if len(fname) != 0 {
		p = &UserPage{Name: fname}
	}
	t, e := template.ParseFiles("./templates/userhome.html")
	if e != nil {
		log.Printf("Parsing userhome.html error: %v", e)
		return
	}
	t.Execute(w, p)
}

// apiHandler 处理api的请求进行代理
func apiHandler(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	if r.Method != http.MethodPost { // 不是POST请求
		re, _ := json.Marshal(ErrorRequestNotRecognized)
		io.WriteString(w, string(re))
		return
	}

	res, _ := ioutil.ReadAll(r.Body)
	apibody := &ApiBody{}
	if err := json.Unmarshal(res, apibody); err != nil {
		re, _ := json.Marshal(ErrorRequestBodyParse)
		io.WriteString(w, string(re))
		return
	}

	request(apibody, w, r)

	defer r.Body.Close()
}

// proxyHandler 代理 127.0.0.1:9000 代理成 127.0.0.1:8080
func proxyHandler(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	u, _ := url.Parse("http://127.0.0.1:9000/")
	proxy := httputil.NewSingleHostReverseProxy(u) //域名转换
	proxy.ServeHTTP(w, r)
}
